<?php
namespace app\adminx\controller;

class Upload extends Admin{

	public function index(){
		return view();
	}

 	#图片上传
 	public function image(){
 		$water = input('get.water',1);
 		$thumb = input('get.thumb',1);
 		$resault = $this->_saveimage("images",$water,$thumb);
 		echo json_encode($resault);
 	}

 	#文件上传
 	public function file(){
 		$resault = $this->_savefile("files");
 		echo json_encode($resault);
 	}

	#保存图片
	private function _saveimage($dir=NULL,$water=0,$thumb=0){
		if(!checkRequest()){
	        return array('state'=>'非法提交');
	    }

		if (empty($dir)) {
			$path = '.'.config('UPLOAD_PATH');
		}else{
			$path = '.'.config('UPLOAD_PATH').$dir.'/';
		}

		if(!is_dir($path)){
    		mkdir($path);
		}

	    $file = request()->file('file');
		$info = $file->move($path);
		if($info){
			$fname=str_replace('\\','/',$info->getSaveName());
			if (empty($dir)) {
				$fname = config('UPLOAD_PATH').$fname;
			}else{
				$fname = config('UPLOAD_PATH').$dir.'/'.$fname;
			}
			
			$result = array(
				'url' => $fname,   //保存后的文件路径
		        'title'    => $info->getInfo()['name'],   //文件描述，对图片来说在前端会添加到title属性上
		        'original' => $info->getInfo()['name'],   //原始文件名
		        'state'    => 'SUCCESS'  //上传状态，成功时返回SUCCESS,其他任何值将原样返回至图片上传框中
			);
			return json_encode(array(
	            'code'=>1,
	            'results'=>array(
	                'data'=>array(
	                    'url'=>$fname
	                    )
	                )
	        ));	
		}else{
			//是专门来获取上传的错误信息的
			return array('code'=>0,'msg'=>$file->getError());
		}		
	}

	#保存文件
	private function _savefile($dir=NULL){
		if (empty($dir)) {
			$path = '.'.C('UPLOAD_PATH');
		}else{
			$path = '.'.C('UPLOAD_PATH').$dir.'/';
		}
		$upload = new \Think\Upload();// 实例化上传类
		$upload->maxSize = C('file_size')*1000;
		$upload->rootPath = $path;
		$upload->autoSub = true;
		$upload->replace=true;     //如果存在同名文件是否进行覆盖
		$upload->exts= explode(',',C('file_exts'));     //准许上传的文件后缀
		$info = $upload->upload();
		if($info){
			foreach($info as $file){
				if (empty($dir)) {
					$url = C('UPLOAD_PATH').$file['savepath'].$file['savename'];
				}else{
					$url = C('UPLOAD_PATH').$dir.'/'.$file['savepath'].$file['savename'];
				}
				$showsize = $file['size'].'Byte';
				$size = $file['size'];
			}
			if($size > 1024){
				$size = round($size/1024,2);
				$showsize = $size . 'KB';
			}

			if($size > 1024){
				$size = round($size/1024,2);
				$showsize = $size . 'MB';
			}

			if($size > 1024){
				$size = round($size/1024,2);
				$showsize = $size . 'GB';
			}
			
			return array('state'=>'SUCCESS','url'=>$url,'size'=>$showsize);

		}else{
			//是专门来获取上传的错误信息的			
			return array('state'=>$upload->getError());
		}
	}
 }

?>